package com.boboPlanet.user.async;

import com.boboPlanet.comm.thread.ThreadPoolTaskExecutorMdcWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author mis_wu
 * @date 2023/2/14 17:51
 * springboot整合线程池
 * 使用:异步执行的方法上 @Async("taskExecutor")
 */
@Configuration
@Slf4j
public class ThreadPoolConfig implements AsyncConfigurer {

    private static final String login_fail_hande = "loginTaskExecute";

    /**
     *   每秒需要多少个线程处理?
     *   tasks/(1/task cost)
     */
    private static final int corePoolSize = 10;

    /**
     * 线程池维护线程的最大数量
     * (max(tasks)- queueCapacity)/(1/task cost)
     */
    private static final int maxPoolSize = 30;

    /**
     * 缓存队列
     * (coreSizePool/task cost)*response time
     */
    private static final int queueCapacity = 10;

    /**
     * 允许的空闲时间 unit:s
     * 默认为60
     */
    private static final int keepAlive = 100;

    @Bean("taskExecutor")
    public TaskExecutor taskExecutor() {
        //异步获取traceId
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutorMdcWrapper();
        // 设置核心线程数  每秒需要多少个线程处理?  tasks/(1/task cost)
        executor.setCorePoolSize(corePoolSize);
        // 设置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 设置队列容量
        executor.setQueueCapacity(queueCapacity);
        // 设置允许的空闲时间（秒）
        executor.setKeepAliveSeconds(keepAlive);
        // 设置默认线程名称
        executor.setThreadNamePrefix("thread-bobo-planet-");
        // 设置拒绝策略rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        return executor;
    }


    /**
     * 线程池处理多任务并行
     * @return ThreadPoolTaskExecutor
     */
    @Bean("multiTaskThreadHandler")
    public ThreadPoolTaskExecutor multiTaskThreadHandler() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutorMdcWrapper();
        //核心线程数目
        executor.setCorePoolSize(16);
        //指定最大线程数
        executor.setMaxPoolSize(64);
        //队列中最大的数目
        executor.setQueueCapacity(16);
        //线程名称前缀
        executor.setThreadNamePrefix("multiTaskThreadHandler_");
        //rejection-policy：当pool已经达到max size的时候，如何处理新任务
        //CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        //对拒绝task的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //线程空闲后的最大存活时间
        executor.setKeepAliveSeconds(60);
        //加载
        executor.initialize();
        return executor;
    }

    /**
     * 指定默认线程池
     * @return Executor
     */
    @Override
    public Executor getAsyncExecutor() {
        return taskExecutor();
    }

    /**
     * todo: 线程池执行任务失败处理
     * @return Async
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex,method,params) -> {
            String name = method.getName();
            if (login_fail_hande.equals(name)){
                log.error("星球用户登录异步缓存失败,原因: {}",ex.getMessage(),ex);
            }
            log.error("thread pool execute task fail,method is: {}, params is: {} ,exception is: {}",method.getName(),params,ex.getMessage());
        };
    }
}
